package tt.dz.egobus.servicemanager.cycle;

import tt.dz.egobus.servicemanager.core.exception.BusinessException;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author Anson
 * @date 17-4-6
 * @name 默认的 执行器
 * @since 1.0.4
 */
public class DefaultAppCycleProcessor implements AppCycleProcessorChain {


    private List<AppCycleProcessor> appCycleProcessorList = new ArrayList<>();

    private AtomicBoolean isProcessor = new AtomicBoolean(false);


    @Override
    public boolean isProcessor() {
        return isProcessor.get();
    }

    @Override
    public boolean processorInit() throws BusinessException {
        if (!this.appCycleProcessorList.isEmpty()) {
            for (AppCycleProcessor appCycleProcessor : this.appCycleProcessorList) {
                if (!appCycleProcessor.isProcessor()) {
                    appCycleProcessor.processorInit();
                }
            }
        }

        isProcessor.set(true);
        return isProcessor.get();
    }

    @Override
    public boolean processorDestroyed() throws BusinessException {
        if (!this.appCycleProcessorList.isEmpty()) {
            for (AppCycleProcessor appCycleProcessor : this.appCycleProcessorList) {
                if (appCycleProcessor.isProcessor()) {
                    appCycleProcessor.processorDestroyed();
                }
            }
        }

        return true;
    }

    @Override
    public void addChain(AppCycleProcessor cycleProcessor) {
        appCycleProcessorList.add(cycleProcessor);
    }
}
